from django.shortcuts import render
from rest_framework.generics import ListAPIView, CreateAPIView, UpdateAPIView, DestroyAPIView
# Create your views here.
from rest_framework.response import Response
from rest_framework_extensions.cache.decorators import cache_response
from rest_framework_extensions.cache.mixins import CacheResponseMixin

from areas.models import Area
from areas.serializers import AreasSerialzier, AddressSerializers
from users.models import Address


class AreasView(CacheResponseMixin, ListAPIView):
    """
        获取所有省的信息
    """
    serializer_class = AreasSerialzier
    queryset = Area.objects.filter(parent=None)


class AreaView(CacheResponseMixin, ListAPIView):
    """
        获取所有市的信息和区县的信息
    """
    serializer_class = AreasSerialzier

    # queryset = Area.objects.filter(parent__id=pk)

    # @cache_response(timeout=60*60,cache='default')
    def get_queryset(self):
        pk = self.kwargs['pk']  # 获取路由中的pk值
        return Area.objects.filter(parent_id=pk)


class AddressView(CreateAPIView, UpdateAPIView, ListAPIView):
    """
        保存地址
    """
    serializer_class = AddressSerializers

    # queryset = Address.objects.filter()

    def get_queryset(self):
        return Address.objects.filter(user=self.request.user, is_deleted=False)

    def delete(self, request, pk):
        obj = self.get_object()

        obj.is_deleted = True
        obj.save()

        return Response()

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())

        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)
        return Response({'addresses': serializer.data, 'default_address_id': self.request.user.default_address_id})
